# -*- coding:utf-8 -*-
import time
import configparser
import os
from urllib.parse import quote
import datetime
import allure
from configs.config import CONFIG_PATH
from tools.logs import Logger
import re
from PIL import Image


def time_format():
    # 返回时间 格式为 2021-06-02-12
    return time.strftime("%Y-%m-%d-%H", time.localtime())


def time_range(index, num):
    """
    当前日期加减天数
    :param index: + 或者 -  +为当前往后推
    :param num:  天数量
    :return: 当前日期, 计算后日期
    """
    now = datetime.datetime.now()
    if index == '+':
        t = now + datetime.timedelta(days=int(num))
    else:
        t = now - datetime.timedelta(days=int(num))
    return now.strftime("%Y-%m-%d"), t.strftime("%Y-%m-%d")


def read_config(p, section, key):
    """
    :param p:  配置文件路径
    :param section:  文件section
    :param key:    取值对应的key
    :return:  key对应value
    """
    conf = configparser.ConfigParser()
    conf.read(p, encoding="utf-8-sig")
    val = conf[section][key]
    return val


def w_logging():
    config_path = CONFIG_PATH
    log_p = read_config(config_path, 'logging', 'path')
    if not os.path.exists(log_p):
        os.makedirs(log_p)
    level = read_config(config_path, 'logging', 'level')
    console_put = read_config(config_path, 'logging', 'console_put')
    log_path = os.path.join(log_p, time_format()  + '.log')
    log_path_err = os.path.join(log_p, time_format() + '_err.log')
    log = Logger(log_path, level=level, console_put=console_put)
    log_err = Logger(log_path_err, level='error', console_put=console_put)
    return log, log_err


def check_msg_result(exp, msg, istrue="True", ignorecase=None):
    """
     *函数说明*:检查预期结果和实际结果是否匹配

        *参数说明*:
              exp: 预期结果, 类型:正则表达式, 必选
              msg: 希望匹配的字符串,类型: str, 必选
              istrue: 设置是否匹配标志,类型: str, 可选
              ignorecase:是否忽略大小写，类型: str（忽略大小写时，参数使用ignorecase）,默认匹配大小写 可选
        *返回值*:  匹配失败则 Fail

    """
    if isinstance(msg, str):
        pass
    else:
        msg = msg.decode('utf-8')

    if ignorecase == 'ignorecase':
        result = re.search(r'%s' % exp, msg, re.IGNORECASE)
    else:
        result = re.search(r'%s' % exp, msg)

    if (result is not None) == (istrue.lower() == 'true'):
        return
    else:
        raise Exception(f'check result failed! 期望：{exp} -> 实际返回：{msg}')


def check_code_result(exp, rst, err_msg = None):
    assert exp == rst, err_msg


def get_image_size(img_path):
    """
    获取图片 宽 长
    :param img_path:  图片路径
    :return:   （宽 长）
    """
    img = Image.open(img_path)
    return img.size[0], img.size[1]


def convert_url(content):
    """
    字符串转url编码
    :param content:
    :return:
    """
    return quote(content)